import axios from 'axios'
import { getToken } from '@/utils/auth'

let http = axios.create({
  baseURL: '/api',
  timeout: 60 * 1000
})

http.interceptors.request.use(config => {
  // 每次请求添加请求记录
  // config.cancelToken = new axios.CancelToken(cancel => window.__axiosPromiseArr.push({ cancel }))
  if (!config.url.endsWith('/login')) {
    config.headers['Authorization'] = `Bearer ${getToken()}`
    config.headers['Content-Type'] = `application/json`
  }
  return config
})

http.interceptors.response.use(res => {
  return res.data
}, error => {
  const status = error.response.status
  if (status === 401) {
    window.location.href = '/login'
    return Promise.reject(error.response.data)
  }
  if (status === 409) {
    return Promise.reject(error.response.data)
  }
  // window.__axiosPromiseArr.forEach((ele, index) => {
  //   ele.cancel()
  //   delete window.__axiosPromiseArr[index]
  // })
  return Promise.reject(error)
})

http.post = (url, data, headers) => {
  return http({
    method: 'post',
    url,
    data,
    headers
  })
},
http.get = (url, params, headers) => {
  return http({
    method: 'get',
    url,
    params,
    headers
  })
},
http.put = (url, data, headers) => {
  return http({
    method: 'put',
    url,
    data,
    headers
  })
},
http.delete = (url, data) => {
  return http({
    method: 'delete',
    url,
    data
  })
},
http.patch = (url, data) => {
  return http({
    method: 'patch',
    url,
    data
  })
}

export default http
